package com.huamoxi.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.huamoxi.consts.TokenConst;
import com.huamoxi.enums.WhiteListEnum;
import com.huamoxi.result.Result;
import com.huamoxi.utils.CacheUtil;
import com.huamoxi.utils.JwtUtil;
import com.huamoxi.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse resp = exchange.getResponse();
        ServerHttpRequest req = exchange.getRequest();

        // 跳过不需要验证的路径
        String url = req.getURI().getPath();
        for (WhiteListEnum whiteList : WhiteListEnum.values()) {
            if (url.equals(whiteList.getPath())) {
                // 如果请求路径在白名单中，直接放行
                logger.info("直接放行,请求路径 --> {}", url);
                return chain.filter(exchange);
            }
        }

        // 获取参数中的 authorization 参数
        String tokenStr = req.getHeaders().getFirst(TokenConst.AUTHENTICATION);
        String token = "";
        if (StrUtil.isNotBlank(tokenStr)) {
            token = tokenStr.split(TokenConst.PREFIX)[1];
        }

        // 判断 authorization 是否命中
        try {
            jwtUtil.verifyToken(token);

            // 验证未报错, 放行
            return chain.filter(exchange);
        } catch (Exception e) {
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            if (e instanceof io.jsonwebtoken.ExpiredJwtException) {
                // token 过期处理
                String msg = JSONUtil.toJsonStr(ResultUtil.fail("登录信息已过期,请重新登录"));
                return resp.writeWith(Mono.just(resp.bufferFactory().wrap(msg.getBytes())));
            }
            // jwt 格式不合法
            String msg = JSONUtil.toJsonStr(ResultUtil.fail("token不合法,请重新登录"));
            return resp.writeWith(Mono.just(resp.bufferFactory().wrap(msg.getBytes())));
        }
    }

    // 设置为优先执行此过滤器
    @Override
    public int getOrder() {
        return -1;
    }
}
